<template>
  <ContentWrap class="chem-record-wrap">
    <div class="header-container-consumable">
      <!-- Title Centered -->
      <h2 class="centered-title-equipment">工作场所空气中的游离二氧化硅含量测定记录表</h2>
    </div>
    <!-- 表格 -->
    <el-table :data="form.table" border class="chem-table" stripe table-layout="fixed">
      <el-table-column align="center" label="序号" type="index" />
      <el-table-column align="center" label="代表/取样场所、岗位、地点" prop="post" >
        <template #default="{ row }">
          <el-input v-model="row.post" placeholder="" :disabled="tbflag"  :title="row.post"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="样品编号" prop="sampleNo" width="170px">
        <template #default="{ row }">
          <el-input v-model="row.sampleNo" placeholder="" :disabled="tbflag" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="样品质量G(g)" prop="sampleMass"  v-if="!tbflag">
        <template #default="{ row }">
          <el-input v-model="row.sampleMass" placeholder="" @input="calculateSiliconContent(row)" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="坩埚加沉淀质量(HF处理前)" v-if="!tbflag">
        <el-table-column align="center" label="m3(g)" prop="m3">
          <template #default="{ row }">
            <el-input v-model="row.m3" placeholder="" @input="calculateM1(row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="m4(g)" prop="m4">
          <template #default="{ row }">
            <el-input v-model="row.m4" placeholder="" @input="calculateM1(row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="平均值m1(g)" prop="m1">
          <template #default="{ row }">
            <el-input v-model="row.m1" placeholder="" readonly @input="calculateM(row)" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="坩埚加沉淀质量(HF处理后)" v-if="!tbflag">
        <el-table-column align="center" label="m5(g)" prop="m5">
          <template #default="{ row }">
            <el-input v-model="row.m5" placeholder="" @input="calculateM2(row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="m6(g)" prop="m6">
          <template #default="{ row }">
            <el-input v-model="row.m6" placeholder="" @input="calculateM2(row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="平均值m2(g)" prop="m2">
          <template #default="{ row }">
            <el-input v-model="row.m2" placeholder="" readonly @input="calculateM(row)" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="沉淀质量m(g)" prop="m" v-if="!tbflag">
        <template #default="{ row }">
          <el-input v-model="row.m" placeholder="" readonly />
        </template>
      </el-table-column>
      <el-table-column align="center" label="游离二氧化硅含量(%)" prop="siliconContent" width="180px" >
        <template #default="{ row }">
          <el-input v-model="row.siliconContent" placeholder="" readonly />
        </template>
      </el-table-column>
      <el-table-column align="center" label="定性结果" prop="selectedHazard" v-if="tbflag">
        <template #default="{ row, $index }">
          <div class="qualitative-result-cell">
            <div>
              <el-button
                type="primary"
                size="small"
                @click="openHazardDialog($index)"
                :class="{ 'warning-button': !row.selectedHazard }"
              >
                {{ row.selectedHazard ? row.selectedHazard.cnName : '定性结果' }}
              </el-button>
            </div>
            <div v-if="!row.selectedHazard && row.siliconContent">
              <span class="warning-text">请选择定性结果</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark" v-if="!tbflag">
        <template #default="{ row }">
          <el-input v-model="row.remark" placeholder="" />
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
  <el-dialog
    v-model.lazy="facilityDialogVisible"
    append-to-body
    destroy-on-close
    title="选择设备"
    width="60%"
  >
    <div class="dialog-content">
      <Facility
        :default-status="1"
        :show-selection="false"
        @selection-change="handleFacilitySelectionChange"
        @handle-facility-confirm="handleFacilityConfirm"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="facilityDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleFacilityConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 危害选择对话框 -->
  <el-dialog
    v-model.lazy="hazardDialogVisible"
    append-to-body
    destroy-on-close
    title="定性结果"
    width="60%"
  >
    <div class="dialog-content">
      <DustSelection @hazard-selected="handleHazardSelected" />
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { ElButton, ElMessage, ElIcon } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import Facility from '@/views/infra/facility/facility.vue'
import DustSelection from './DustSelection.vue'
import { merge } from 'lodash-es'

const route = useRoute()
const router = useRouter()
const props = defineProps<{
  silicaItem?: Record<string, any>
  tbflag?: boolean
}>()

const emit = defineEmits(['change'])
const form = ref({
  projectId: route.query.projectId,
  instrumentInfo: '',
  testStandard: 'GBZ/T192.4-2007',
  testDate: new Date().toISOString().split('T')[0],
  humidity: '',
  temperature: '',
  sampleDate: '',
  table: [
    {
      sampleNo: '',
      post: '',
      sampleMass: '',
      m3: '',
      m4: '',
      m1: '',
      m5: '',
      m6: '',
      m2: '',
      m: '',
      siliconContent: '',
      selectedHazard: null,
      remark: ''
    }
  ]
})
const loading = ref(false)
const facilityDialogVisible = ref(false)
const selectedFacility = ref<any>(null)
const hazardDialogVisible = ref(false)
const currentRowIndex = ref<number>(-1)

// 计算m1平均值（m3和m4的平均值）
const calculateM1 = (row: any) => {
  const m3 = parseFloat(row.m3?.toString().replace(/\s/g, '')) || 0
  const m4 = parseFloat(row.m4?.toString().replace(/\s/g, '')) || 0
  console.log('m3:', m3)
  console.log('m4:', m4)
  if (m3 > 0 && m4 > 0) {
    row.m1 = ((m3 + m4) / 2).toFixed(4)
  } else {
    row.m1 = ''
  }
  // 计算完m1后，重新计算m
  calculateM(row)
}

// 计算m2平均值（m5和m6的平均值）
const calculateM2 = (row: any) => {
  const m5 = parseFloat(row.m5?.toString().replace(/\s/g, '')) || 0
  const m6 = parseFloat(row.m6?.toString().replace(/\s/g, '')) || 0
  if (m5 > 0 && m6 > 0) {
    row.m2 = ((m5 + m6) / 2).toFixed(4)
  } else {
    row.m2 = ''
  }
  // 计算完m2后，重新计算m
  calculateM(row)
}

// 计算沉淀质量m = m1 - m2
const calculateM = (row: any) => {
  const m1 = parseFloat(row.m1?.toString().replace(/\s/g, '')) || 0
  const m2 = parseFloat(row.m2?.toString().replace(/\s/g, '')) || 0
  if (m1 > 0 && m2 > 0) {
    // 校验 m1 应始终大于等于 m2
    if (m1 < m2) {
      ElMessage.error('平均值m1(g)应大于等于平均值m2(g)，请检查数据')
      row.m = ''
      row.siliconContent = ''
      return
    }
    row.m = (m1 - m2).toFixed(4)
  } else {
    row.m = ''
  }
  // 计算完m后，重新计算游离二氧化硅含量
  calculateSiliconContent(row)
}

const calculateSiliconContent = (row: any) => {
  const m = parseFloat(row.m?.toString().replace(/\s/g, '')) || 0
  const sampleMass = parseFloat(row.sampleMass?.toString().replace(/\s/g, '')) || 0
  if (m > 0 && sampleMass > 0) {
    const percent = (m / sampleMass) * 100
    // 校验 百分比应在 0-100% 之间
    if (percent < 0 || percent > 100) {
      ElMessage.error('数据异常，游离二氧化硅含量(%)不在0-100% 之间')
      row.siliconContent = ''
      return
    }
    row.siliconContent = percent.toFixed(4)
  } else {
    row.siliconContent = ''
  }
}

const openFacilityDialog = () => {
  facilityDialogVisible.value = true
}
const handleFacilitySelectionChange = (selection: any[]) => {
  const facility = Array.isArray(selection[0]) ? selection[0][0] : selection[0]
  selectedFacility.value = facility || null
}

const handleFacilityConfirm = () => {
  console.log('确认选择设备:', JSON.stringify(selectedFacility.value))
  if (selectedFacility.value) {
    form.value.instrumentInfo =
      selectedFacility.value.name +
      '/' +
      selectedFacility.value.model +
      '/' +
      selectedFacility.value.serialNumber
    console.log('选择设备form:', JSON.stringify(form.value))
    console.log('选择设备:', JSON.stringify(selectedFacility.value))
    facilityDialogVisible.value = false
    selectedFacility.value = null
    ElMessage.success('选择设备成功')
  } else {
    ElMessage.warning('请选择设备')
  }
}

// 打开危害选择对话框
const openHazardDialog = (rowIndex: number) => {
  currentRowIndex.value = rowIndex
  hazardDialogVisible.value = true
}

// 处理危害选择
const handleHazardSelected = (hazard: any) => {
  if (currentRowIndex.value >= 0 && currentRowIndex.value < form.value.table.length) {
    form.value.table[currentRowIndex.value].selectedHazard = hazard
    ElMessage.success(`已选择危害: ${hazard.cnName}`)
  }
  hazardDialogVisible.value = false
  currentRowIndex.value = -1
}

watch(
  () => props.silicaItem,
  (newValue, oldValue) => {
    console.log('form changed1111:', newValue)
    // 在这里执行你的逻辑
    form.value = merge({}, form.value, newValue)
    if (!loading.value) {
      loading.value = false
    }
  },
  { deep: true, immediate: true } // 深度监听，因为 form 是嵌套对象
)

watch(
  form,
  (newVal) => {
    emit('change', newVal)
    console.log('表单数据全部变化111:', JSON.stringify(newVal))
  },
  { deep: true }
)

// 允许父组件通过 ref 访问并设置表单
defineExpose({ form })
</script>

<style lang="scss" scoped>
.header-container-consumable {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e6eb;
}

.centered-title-equipment {
  text-align: center; // Center the text
  flex-grow: 1; // Allow title to take available space to help centering
  margin: 0; // Remove default margin
  font-size: 24px; // Match Consumable title size
  font-weight: bold;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

:deep(.el-input__inner) {
  text-align: center;
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}

.qualitative-result-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-left: 60px;
}

</style>
